package com.gm.sfc.util;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.database.Cursor;
import android.database.DatabaseUtils;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.view.View;

import com.gm.sfc.field.DbColumnField;
import com.gm.sfc.field.IField;

/**
 * Utilクラス
 * @author $Author: segen.der.gottin@gmail.com $
 * @version $Revision: 16 $
 */
public class Utility {
    /**
     * StringのNull・Blunkチェック
     * @param str 文字列
     * @return true:null有り　false:nullなし
     */
    public static boolean isEmpty(String str) {
        if (str == null || str.trim().length() == 0) {
            return true;
        }
        return false;
    }

    /**
     * ListのNull・Blunkチェック
     * @param str 文字列
     * @return true:null有り　false:nullなし
     */
    public static boolean isEmpty(List<?> list) {
        if (list == null || list.size() == 0) {
            return true;
        }
        return false;
    }

    /**
     * ObjectのNull・Blunkチェック
     * @param str 文字列
     * @return true:null有り　false:nullなし
     */
    public static boolean isEmpty(Object obj) {
        if (obj == null || obj.toString().trim().length() == 0) {
            return true;
        }
        return false;
    }

    /**
     * 0 or 1で来る数値をBooleanに変換
     */
    public static boolean changeIntBool(String str) {
        return Integer.parseInt(str) == 0 ? false : true;
    }

    /**
     * 0 or 1で来る数値をBooleanに変換
     */
    public static boolean changeIntBool(Object obj) {
        if (isEmpty(obj)) {
            return false;
        }
        return changeIntBool(obj.toString());
    }

    /**
     * true : falseを数値に変換
     */
    public static int changeBoolInt(boolean bool) {
        return bool ? 1 : 0;
    }

    public static void putHashMap(HashMap<IField, Object> hashmap, IField field, Object object) {
        if (object == null) {
            hashmap.put(field, "");
        } else {
            hashmap.put(field, object);
        }
        return;
    }

    public static String getDataFromMap(HashMap<IField, Object> hashmap, IField field) {
        if (hashmap.containsKey(field)) {
            if (hashmap.get(field) == null) {
                return "''";
            }
            String str = hashmap.get(field).toString();
            if (str == null) {
                return "''";
            } else {
                str = DatabaseUtils.sqlEscapeString(str);
            }
            return str;
        }
        return "''";
    }

    /**
     * HashMapから文字列を取得する
     * @param hashmap HashMap
     * @param field Field
     * @return 文字列
     */
    public static String getHashmap(HashMap<IField, Object> hashmap, IField field) {
        if (hashmap != null && hashmap.containsKey(field)) {
            Object object = hashmap.get(field);
            String str = object == null ? "" : object.toString();
            if (str == null) {
                return "";
            }
            return str;
        }
        return "";
    }

    /**
     * TODO Auto-generated constructor stub
     * @param hashMap
     * @param field
     * @return
     */
    public static String[] getHashmapStrs(HashMap<IField, Object> hashMap, IField field) {
        if (hashMap != null && hashMap.containsKey(field)) {
            Object object = hashMap.get(field);

            if (object != null && object instanceof String[]) {
                return (String[]) object;
            }
        }
        return null;
    }

    /**
     * 少数点の文字列をフォーマット
     * @param str 小数点文字列
     * @return　%03d.%02d
     */
    public static String formatDouble(String str) {
        return formatDouble(str, "000.00");
    }

    /**
     * 少数点の文字列をフォーマット
     * @param str 小数点文字列
     * @return　%03d.%02d
     */
    public static String formatDouble(String str, String format) {
        try {
            DecimalFormat df = new DecimalFormat(format);
            BigDecimal bigDecimal = new BigDecimal(str);
            String[] split = format.replace(".", "-").split("-");
            return df.format(bigDecimal.setScale(split[1].length(), BigDecimal.ROUND_DOWN)).replace(",", ".");
        } catch (Exception e) {
            return format;
        }
    }

    public static boolean getBoolean(String str) {
        try {
            int parseInt = Integer.parseInt(str);
            return parseInt == 0 ? true : false;
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * HashMapから文字列を取得する<br>
     * デフォルト０
     * @param hashmap HashMap
     * @param field Field
     * @return 文字列
     */
    public static String getHashmapIntStr(HashMap<IField, Object> hashmap, IField field) {
        if (hashmap != null && hashmap.containsKey(field)) {
            Object object = hashmap.get(field);
            if (isEmpty(object)) {
                return "0";
            }
            return object.toString();
        }
        return "0";
    }

    /**
     * HashMapから数値を取得する<br>
     * @param hashmap HashMap
     * @param field Field
     * @return 文字列
     */
    public static int getHashmapInt(HashMap<IField, Object> hashmap, IField field) {
        if (hashmap != null && hashmap.containsKey(field)) {
            Object object = hashmap.get(field);
            if (isEmpty(object)) {
                return 0;
            }
            return Integer.parseInt(object.toString());
        }
        return 0;
    }

    /**
     * HashMapから数値を取得する<br>
     * @param hashmap HashMap
     * @param field Field
     * @return 文字列
     */
    public static Double getHashmapDouble(HashMap<IField, Object> hashmap, IField field) {
        if (hashmap != null && hashmap.containsKey(field)) {
            Object object = hashmap.get(field);
            if (isEmpty(object)) {
                return 0.0d;
            }
            return Double.valueOf(object.toString());
        }
        return 0.0d;
    }

    /**
     * HashMapから数値を取得する<br>
     * @param hashmap HashMap
     * @param field Field
     * @return 文字列
     */
    public static Float getHashmapFloat(HashMap<IField, Object> hashmap, IField field) {
        if (hashmap != null && hashmap.containsKey(field)) {
            Object object = hashmap.get(field);
            if (isEmpty(object)) {
                return 0.0f;
            }
            return Float.valueOf(object.toString());
        }
        return 0.0f;
    }

    /**
     * HashMapから数値を取得する<br>
     * @param hashmap HashMap
     * @param field Field
     * @return 文字列
     */
    public static Long getHashmapLong(HashMap<IField, Object> hashmap, IField field) {
        if (hashmap != null && hashmap.containsKey(field)) {
            Object object = hashmap.get(field);
            if (isEmpty(object)) {
                return 1l;
            }
            return Long.valueOf(object.toString());
        }
        return 1l;
    }

    public static HashMap<IField, Object> convertToHashmap(Cursor cursor) {

        HashMap<IField, Object> hashmap = new HashMap<IField, Object>();
        int columnCount = cursor.getColumnCount();
        for (int columnIndex = 0; columnIndex < columnCount; columnIndex++) {
            String name = cursor.getColumnNames()[columnIndex];
            if (DbColumnField.valueOf(name) == DbColumnField.id
                    || DbColumnField.valueOf(name) == DbColumnField.active_flag
                    || DbColumnField.valueOf(name) == DbColumnField.delete_flag) {
                hashmap.put(DbColumnField.valueOf(name), cursor.getInt(columnIndex));
            } else {
                hashmap.put(DbColumnField.valueOf(name), cursor.getString(columnIndex));
            }
        }
        return hashmap;
    }

    public static String getResString(Context context, int resId) {
        return context.getString(resId);
    }

    @SuppressWarnings("unchecked")
    public static LinkedList<byte[]> getListFormHashmap(HashMap<IField, Object> hashmap, IField field) {
        if (hashmap != null && hashmap.containsKey(field)) {
            Object object = hashmap.get(field);
            if (object != null && object instanceof LinkedList<?>) {
                return (LinkedList<byte[]>) object;
            }
        }
        return null;
    }

    /**
     * ネットワーク状況の確認
     * @param context コンテキスト
     * @return true:接続有り　false：接続なし
     */
    public static boolean isConnected(Context context) {
        ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo ni = cm.getActiveNetworkInfo();
        if (ni != null) {
            return cm.getActiveNetworkInfo().isConnected();
        }
        return false;
    }

    public static int getPercent(int complete, int total) {
        return ((total - complete) * 100 / total);
    }

    @SuppressWarnings("unchecked")
    public static <T extends View> T customFindViewById(View v, int id) {
        return (T) v.findViewById(id);
    }

    @SuppressWarnings("unchecked")
    public static <T extends View> T customFindViewById(Activity a, int id) {
        return (T) a.findViewById(id);
    }

    @SuppressWarnings("unchecked")
    public static <T extends View> T customFindViewById(Dialog a, int id) {
        return (T) a.findViewById(id);
    }

    /**
     * アプリのバージョン情報を取得
     * @param context
     * @return
     */
    public static String getAppVersion(Context context) {
        PackageManager pm = context.getPackageManager();
        try {
            PackageInfo pi = pm.getPackageInfo(context.getPackageName(),
                    PackageManager.GET_META_DATA);
            return pi.versionName;
        } catch (NameNotFoundException e) {
        }
        return "0.0.0";
    }

    public static String convertFileToStr(File file) throws IOException {
        BufferedReader reader = null;
        try {
            reader = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
            StringBuilder builder = new StringBuilder();
            int c;
            while ((c = reader.read()) != -1) {
                builder.append((char) c);
            }
            return builder.toString();
        } finally {
            reader.close();
        }
    }

    public static String getUnknownText(String text) {
        if (Utility.isEmpty(text)) {
            return text;
        }
        if (text.equals("<unknown>")) {
            return "不明";
        }
        return text;
    }
}
